<template>
  <div class="app-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>司机管理</el-breadcrumb-item>
      <el-breadcrumb-item>司机详情</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span>司机详情</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          icon="el-icon-arrow-left"
          @click="goBack"
        >
          返回司机列表
        </el-button>
      </div>

      <!-- 标签页切换 -->
      <el-tabs v-model="activeTab" type="border-card" style="margin-top: 20px">
        <el-tab-pane label="司机信息" name="driverInfo">
          <div v-if="driverInfo" class="driver-info-content">
            <el-table :data="driverInfoData" border style="width: 100%">
              <el-table-column
                prop="label"
                label="信息项"
                width="180"
              ></el-table-column>
              <el-table-column prop="value" label="内容">
                <template slot-scope="scope">
                  <div v-if="scope.row.tagType">
                    <dict-tag
                      v-if="scope.row.tagType === 'gender'"
                      :options="dict.type.gender"
                      :value="scope.row.value"
                    />
                    <dict-tag
                      v-else-if="scope.row.tagType === 'driver_status'"
                      :options="dict.type.driver_status"
                      :value="scope.row.value"
                    />
                    <dict-tag
                      v-else-if="scope.row.tagType === 'work_status'"
                      :options="dict.type.work_status"
                      :value="scope.row.value"
                    />
                  </div>
                  <span v-else>
                    {{ scope.row.value }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else class="no-data">
            <el-empty description="暂无数据"></el-empty>
          </div>
        </el-tab-pane>
        <el-tab-pane label="解除/绑定车辆" name="vehicleBind">
          <div class="tab-content">
            <el-table :data="vehicleData" border style="width: 100%">
              <el-table-column
                prop="vehicleId"
                label="车辆ID"
                width="120"
              ></el-table-column>
              <el-table-column
                prop="plateNumber"
                label="车牌号"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="vehicleType"
                label="车辆类型"
              ></el-table-column>
              <el-table-column
                prop="vehicleLevel"
                label="车辆级别"
              ></el-table-column>
              <el-table-column
                prop="bindTime"
                label="绑定时间"
              ></el-table-column>
              <el-table-column label="操作" width="100" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleUnbind(scope.row)"
                    >解除绑定</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 15px">
              <el-button type="primary" @click="handleBindVehicle"
                >绑定新车辆</el-button
              >
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="查看营业额" name="revenue">
          <div class="tab-content">
            <div class="search-area">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 300px"
              ></el-date-picker>
              <el-button
                type="primary"
                style="margin-left: 10px"
                @click="searchRevenue"
                >查询</el-button
              >
            </div>
            <el-table
              :data="revenueData"
              border
              style="width: 100%; margin-top: 15px"
            >
              <el-table-column
                prop="date"
                label="日期"
                width="150"
              ></el-table-column>
              <el-table-column
                prop="orderCount"
                label="订单数"
              ></el-table-column>
              <el-table-column
                prop="totalAmount"
                label="总金额"
                width="120"
              ></el-table-column>
              <el-table-column
                prop="commission"
                label="佣金"
                width="120"
              ></el-table-column>
              <el-table-column
                prop="driverIncome"
                label="司机收入"
                width="120"
              ></el-table-column>
            </el-table>
            <div style="margin-top: 15px; text-align: right">
              <el-descriptions border column="2">
                <el-descriptions-item label="订单总数">{{
                  totalOrderCount
                }}</el-descriptions-item>
                <el-descriptions-item label="总金额">{{
                  totalAmount
                }}</el-descriptions-item>
                <el-descriptions-item label="总佣金">{{
                  totalCommission
                }}</el-descriptions-item>
                <el-descriptions-item label="司机总收入">{{
                  totalDriverIncome
                }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="顺风单地址" name="address">
          <div class="tab-content">
            <el-table :data="addressData" border style="width: 100%">
              <el-table-column
                prop="addressId"
                label="地址ID"
                width="120"
              ></el-table-column>
              <el-table-column
                prop="addressName"
                label="地址名称"
              ></el-table-column>
              <el-table-column
                prop="addressType"
                label="地址类型"
              ></el-table-column>
              <el-table-column
                prop="latitude"
                label="纬度"
                width="120"
              ></el-table-column>
              <el-table-column
                prop="longitude"
                label="经度"
                width="120"
              ></el-table-column>
              <el-table-column label="操作" width="180" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="viewMap(scope.row)"
                    >查看地图</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    @click="editAddress(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    @click="deleteAddress(scope.row)"
                    style="color: #f56c6c"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 15px">
              <el-button type="primary" @click="addAddress">新增地址</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { getDriver } from "@/api/driver/driver";
import { getDicts } from "@/api/system/dict/data";
import DictTag from "@/components/DictTag";

export default {
  name: "DriverDetail",
  components: {
    DictTag,
  },
  data() {
    return {
      driverId: null,
      driverInfo: null,
      dict: {
        type: {
          gender: [],
          driver_status: [],
          work_status: [],
        },
      },
      // 标签页相关
      activeTab: "driverInfo",
      // 司机信息表格数据
      driverInfoData: [],
      // 车辆绑定数据
      vehicleData: [],
      // 营业额数据
      revenueData: [],
      dateRange: [],
      totalOrderCount: 0,
      totalAmount: 0,
      totalCommission: 0,
      totalDriverIncome: 0,
      // 地址数据
      addressData: [],
    };
  },
  created() {
    // 从路由参数中获取司机ID
    this.driverId = this.$route.query.driverId;
    if (this.driverId) {
      this.getDriverDetail();
      this.getVehicleData();
      this.getRevenueData();
      this.getAddressData();
    }
    this.initDicts();
  },
  methods: {
    // 获取司机详情
    getDriverDetail() {
      getDriver(this.driverId)
        .then((response) => {
          this.driverInfo = response.data;
          // 转换为表格数据格式
          this.formatDriverInfoToTable();
        })
        .catch((error) => {
          this.$message.error("获取司机详情失败");
          console.error("获取司机详情失败:", error);
        });
    },

    // 格式化司机信息为表格数据
    formatDriverInfoToTable() {
      if (!this.driverInfo) return;

      this.driverInfoData = [
        { label: "司机姓名", value: this.driverInfo.driverName },
        {
          label: "司机性别",
          value: this.driverInfo.driverSex,
          tagType: "gender",
        },
        { label: "手机号码", value: this.driverInfo.driverPhone },
        { label: "身份证号", value: this.driverInfo.card },
        {
          label: "注册时间",
          value: this.parseTime(this.driverInfo.registrationTime),
        },
        { label: "城市", value: this.driverInfo.cityId },
        { label: "绑定车辆", value: this.driverInfo.bindVehicle },
        { label: "车辆级别", value: this.driverInfo.vehicleLevel },
        {
          label: "司机状态",
          value: this.driverInfo.driverStatus,
          tagType: "driver_status",
        },
        {
          label: "工作状态",
          value: this.driverInfo.workStatus,
          tagType: "work_status",
        },
        { label: "司机主管", value: this.driverInfo.userId },
        { label: "合同有效期起", value: this.driverInfo.contractStartDate },
        { label: "合同有效期止", value: this.driverInfo.contractEndDate },
      ];
    },

    // 获取车辆绑定数据
    getVehicleData() {
      // 这里应该是实际的API调用，目前使用模拟数据
      this.vehicleData = [
        {
          vehicleId: "V001",
          plateNumber: "京A12345",
          vehicleType: "轿车",
          vehicleLevel: "舒适型",
          bindTime: "2023-01-15",
        },
        {
          vehicleId: "V002",
          plateNumber: "京B67890",
          vehicleType: "SUV",
          vehicleLevel: "豪华型",
          bindTime: "2023-03-20",
        },
      ];
    },

    // 获取营业额数据
    getRevenueData() {
      // 这里应该是实际的API调用，目前使用模拟数据
      this.revenueData = [
        {
          date: "2023-06-01",
          orderCount: 15,
          totalAmount: 3200,
          commission: 480,
          driverIncome: 2720,
        },
        {
          date: "2023-06-02",
          orderCount: 18,
          totalAmount: 3800,
          commission: 570,
          driverIncome: 3230,
        },
        {
          date: "2023-06-03",
          orderCount: 12,
          totalAmount: 2600,
          commission: 390,
          driverIncome: 2210,
        },
        {
          date: "2023-06-04",
          orderCount: 20,
          totalAmount: 4200,
          commission: 630,
          driverIncome: 3570,
        },
        {
          date: "2023-06-05",
          orderCount: 16,
          totalAmount: 3400,
          commission: 510,
          driverIncome: 2890,
        },
      ];

      // 计算总计
      this.calculateRevenueSummary();
    },

    // 计算营业额总计
    calculateRevenueSummary() {
      this.totalOrderCount = this.revenueData.reduce(
        (sum, item) => sum + item.orderCount,
        0
      );
      this.totalAmount = this.revenueData.reduce(
        (sum, item) => sum + item.totalAmount,
        0
      );
      this.totalCommission = this.revenueData.reduce(
        (sum, item) => sum + item.commission,
        0
      );
      this.totalDriverIncome = this.revenueData.reduce(
        (sum, item) => sum + item.driverIncome,
        0
      );
    },

    // 查询营业额
    searchRevenue() {
      // 实际项目中应该根据dateRange参数调用API
      this.getRevenueData();
      this.$message.success("查询成功");
    },

    // 获取地址数据
    getAddressData() {
      // 这里应该是实际的API调用，目前使用模拟数据
      this.addressData = [
        {
          addressId: "A001",
          addressName: "北京西站",
          addressType: "常用地点",
          latitude: "39.8948",
          longitude: "116.3223",
        },
        {
          addressId: "A002",
          addressName: "北京南站",
          addressType: "常用地点",
          latitude: "39.8651",
          longitude: "116.3784",
        },
        {
          addressId: "A003",
          addressName: "首都机场T3",
          addressType: "常用地点",
          latitude: "40.0801",
          longitude: "116.5849",
        },
      ];
    },

    // 解除车辆绑定
    handleUnbind(row) {
      this.$confirm("确定要解除该车辆的绑定吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 实际项目中应该调用解除绑定的API
          this.vehicleData = this.vehicleData.filter(
            (item) => item.vehicleId !== row.vehicleId
          );
          this.$message.success("解除绑定成功");
        })
        .catch(() => {
          this.$message.info("已取消解除绑定");
        });
    },

    // 绑定新车辆
    handleBindVehicle() {
      // 实际项目中应该打开绑定车辆的弹窗或跳转到绑定页面
      this.$message.info("打开绑定车辆界面");
    },

    // 查看地图
    viewMap(row) {
      // 实际项目中应该打开地图查看界面
      this.$message.info(`查看${row.addressName}的地图位置`);
    },

    // 编辑地址
    editAddress(row) {
      // 实际项目中应该打开编辑地址的弹窗
      this.$message.info(`编辑地址${row.addressName}`);
    },

    // 删除地址
    deleteAddress(row) {
      this.$confirm("确定要删除该地址吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 实际项目中应该调用删除地址的API
          this.addressData = this.addressData.filter(
            (item) => item.addressId !== row.addressId
          );
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 新增地址
    addAddress() {
      // 实际项目中应该打开新增地址的弹窗
      this.$message.info("打开新增地址界面");
    },

    // 初始化字典数据
    initDicts() {
      getDicts("gender").then((response) => {
        this.dict.type.gender = response.data;
      });
      getDicts("driver_status").then((response) => {
        this.dict.type.driver_status = response.data;
      });
      getDicts("work_status").then((response) => {
        this.dict.type.work_status = response.data;
      });
    },

    // 返回上一页
    goBack() {
      this.$router.back();
    },

    // 格式化时间
    parseTime(time, pattern) {
      if (time == null || time === 0) {
        return "";
      }
      const date = new Date(time);
      pattern = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
      const format = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
      };
      const formatted = pattern.replace(
        /\{(y|m|d|h|i|s|a)+\}/g,
        (result, key) => {
          let value = format[key];
          if (key === "a") {
            return ["日", "一", "二", "三", "四", "五", "六"][value];
          }
          if (result.length > 0 && value < 10) {
            value = "0" + value;
          }
          return value || 0;
        }
      );
      return formatted;
    },
  },
};
</script>

<style scoped>
.tab-content {
  padding: 20px 0;
}

.driver-info-content {
  margin-top: 20px;
}

.search-area {
  margin-bottom: 15px;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}
</style>
